

#include <dpl/log.h>

D_LOG_DOMAIN(hash_test,"this is a case, how to use");




#include <dpl/hash.h>
#include <dpl/log.h>


#define HASH_COUNT  31

static int hash_test_with_key(dpl_pool_t *pool, unsigned char key)
{
    dpl_hash_table_t *ht;
    unsigned value = 0x12345;
    dpl_hash_iterator_t it_buf, *it;
    unsigned *entry;

    ht = dpl_hash_create(pool, HASH_COUNT);
    if (!ht)
	return -10;

    dpl_hash_set(pool, ht, &key, sizeof(key), 0, &value);

    entry = (unsigned*) dpl_hash_get(ht, &key, sizeof(key), NULL);
    if (!entry)
	return -20;

    if (*entry != value)
	return -30;

    if (dpl_hash_count(ht) != 1)
	return -30;

    it = dpl_hash_first(ht, &it_buf);
    if (it == NULL)
	return -40;

    entry = (unsigned*) dpl_hash_this(ht, it);
    if (!entry)
	return -50;

    if (*entry != value)
	return -60;

    it = dpl_hash_next(ht, it);
    if (it != NULL)
	return -70;

    /* Erase item */

    dpl_hash_set(NULL, ht, &key, sizeof(key), 0, NULL);

    if (dpl_hash_get(ht, &key, sizeof(key), NULL) != NULL)
	return -80;

    if (dpl_hash_count(ht) != 0)
	return -90;

    it = dpl_hash_first(ht, &it_buf);
    if (it != NULL)
	return -100;

    return 0;
}


static int hash_collision_test(dpl_pool_t *pool)
{
    enum {
	COUNT = HASH_COUNT * 4
    };
    dpl_hash_table_t *ht;
    dpl_hash_iterator_t it_buf, *it;
    unsigned char *values;
    unsigned i;

    ht = dpl_hash_create(pool, HASH_COUNT);
    if (!ht)
	return -200;

    values = (unsigned char*) malloc( COUNT);

    for (i=0; i<COUNT; ++i) {
	values[i] = (unsigned char)i;
	dpl_hash_set(pool, ht, &i, sizeof(i), 0, &values[i]);
    }

    if (dpl_hash_count(ht) != COUNT)
	return -210;

    for (i=0; i<COUNT; ++i) {
	unsigned char *entry;
	entry = (unsigned char*) dpl_hash_get(ht, &i, sizeof(i), NULL);
	if (!entry)
	    return -220;
	if (*entry != values[i])
	    return -230;
    }

    i = 0;
    it = dpl_hash_first(ht, &it_buf);
    while (it) {
	++i;
	it = dpl_hash_next(ht, it);
    }

    if (i != COUNT)
	return -240;

    return 0;
}


/*
 * Hash table test.
 */
int test_hash(void)
{

	dpl_i("Enter test!");
   // dpl_pool_t *pool = dpl_pool_create(mem, "hash", 512, 512, NULL);
   dpl_pool_t pool;
    int rc;
    unsigned i;

    /* Test to fill in each row in the table */
    for (i=0; i<=HASH_COUNT; ++i) {
	rc = hash_test_with_key(&pool, (unsigned char)i);
	if (rc != 0) {
	    //dpl_pool_release(pool);
	    return rc;
	}
    }

    /* Collision test */
    rc = hash_collision_test(pool);
    if (rc != 0) {
	//dpl_pool_release(pool);
	return rc;
    }

    //dpl_pool_release(pool);
    return 0;
}



